package com.mentalhealth.diary.controller;

import com.mentalhealth.diary.common.R;
import com.mentalhealth.diary.entity.Member;
import com.mentalhealth.diary.entity.MemberPackage;
import com.mentalhealth.diary.entity.PaymentRecord;
import com.mentalhealth.diary.mapper.MemberMapper;
import com.mentalhealth.diary.mapper.MemberPackageMapper;
import com.mentalhealth.diary.mapper.PaymentRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 会员控制器
 * 处理会员状态管理、开通、续费等功能
 */
@RestController
@RequestMapping("/api/member")
public class MemberController {

    @Autowired
    private MemberMapper memberMapper;
    
    @Autowired
    private MemberPackageMapper memberPackageMapper;
    
    @Autowired
    private PaymentRecordMapper paymentRecordMapper;
    
    /**
     * 获取会员套餐列表
     * @return 套餐列表
     */
    @GetMapping("/packages")
    public R<List<MemberPackage>> getMemberPackages() {
        List<MemberPackage> packages = memberPackageMapper.selectList(null);
        return R.success(packages);
    }
    
    /**
     * 获取用户会员信息
     * @param userId 当前用户ID
     * @return 会员信息
     */
    @GetMapping("/info")
    public R<Member> getMemberInfo(@RequestAttribute("userId") Long userId) {
        Member member = memberMapper.selectByUserId(userId);
        if (member == null) {
            // 返回默认非会员状态
            member = new Member();
            member.setUserId(userId);
            member.setMemberType(0); // 0表示非会员
            member.setStatus(0);
        }
        return R.success(member);
    }
    
    /**
     * 开通/续费会员
     * @param requestData 请求数据
     * @param userId 当前用户ID
     * @return 开通结果
     */
    @PostMapping("/subscribe")
    public R<Map<String, Object>> subscribe(@RequestBody Map<String, Object> requestData, 
                                          @RequestAttribute("userId") Long userId) {
        Long packageId = Long.valueOf(requestData.get("packageId").toString());
        
        // 获取套餐信息
        MemberPackage memberPackage = memberPackageMapper.selectById(packageId);
        if (memberPackage == null) {
            return R.error("套餐不存在");
        }
        
        // 查询用户现有会员信息
        Member member = memberMapper.selectByUserId(userId);
        Date now = new Date();
        
        if (member == null) {
            // 新开通会员
            member = new Member();
            member.setUserId(userId);
            member.setMemberType(memberPackage.getType());
            member.setStartDate(now);
            member.setEndDate(new Date(now.getTime() + memberPackage.getValidDays() * 24 * 60 * 60 * 1000));
            member.setCreateTime(now);
            member.setStatus(1);
            memberMapper.insert(member);
        } else {
            // 续费会员
            Date endDate = member.getEndDate();
            if (endDate.before(now)) {
                // 会员已过期，从当前时间开始计算
                member.setEndDate(new Date(now.getTime() + memberPackage.getValidDays() * 24 * 60 * 60 * 1000));
            } else {
                // 会员未过期，累加时长
                member.setEndDate(new Date(endDate.getTime() + memberPackage.getValidDays() * 24 * 60 * 60 * 1000));
            }
            member.setMemberType(memberPackage.getType());
            member.setUpdateTime(now);
            member.setStatus(1);
            memberMapper.updateById(member);
        }
        
        // 创建支付记录
        PaymentRecord paymentRecord = new PaymentRecord();
        paymentRecord.setUserId(userId);
        paymentRecord.setOrderNo(generateOrderNo());
        paymentRecord.setPackageId(packageId);
        paymentRecord.setAmount(memberPackage.getPrice());
        paymentRecord.setPaymentStatus(1); // 1表示支付成功
        paymentRecord.setCreateTime(now);
        paymentRecordMapper.insert(paymentRecord);
        
        // 构建返回结果
        Map<String, Object> result = new java.util.HashMap<>();
        result.put("member", member);
        result.put("orderNo", paymentRecord.getOrderNo());
        
        return R.success(result);
    }
    
    /**
     * 取消自动续费
     * @param userId 当前用户ID
     * @return 取消结果
     */
    @PostMapping("/cancel-auto-renew")
    public R<String> cancelAutoRenew(@RequestAttribute("userId") Long userId) {
        Member member = memberMapper.selectByUserId(userId);
        if (member == null) {
            return R.error("不是会员");
        }
        
        member.setAutoRenew(0); // 0表示关闭自动续费
        member.setUpdateTime(new Date());
        
        int result = memberMapper.updateById(member);
        if (result > 0) {
            return R.success("取消自动续费成功");
        } else {
            return R.error("取消失败，请稍后重试");
        }
    }
    
    /**
     * 获取支付记录
     * @param userId 当前用户ID
     * @return 支付记录列表
     */
    @GetMapping("/payment-records")
    public R<List<PaymentRecord>> getPaymentRecords(@RequestAttribute("userId") Long userId) {
        Map<String, Object> params = new java.util.HashMap<>();
        params.put("userId", userId);
        
        List<PaymentRecord> records = paymentRecordMapper.selectList(params);
        return R.success(records);
    }
    
    /**
     * 生成订单号
     * @return 订单号
     */
    private String generateOrderNo() {
        String timestamp = String.valueOf(System.currentTimeMillis());
        String random = UUID.randomUUID().toString().substring(0, 6).toUpperCase();
        return "ORD" + timestamp + random;
    }
}